package com.czy.owner.ui.workorder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.OrderMultiStyleAdapter;
import com.czy.owner.adapter.OrderMultiStyleAdapter2;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyOrderModel;
import com.czy.owner.entity.WorkOrderModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.workorder.OrderDetailActivity2;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by hedepu on 2017/9/8 0008.
 * 全部订单
 */
public class OrderFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private OrderMultiStyleAdapter2 adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private String status = "";
    private List<WorkOrderModel> dataList = new ArrayList<>();
    public static String unPaidDepositTime = "2";

    public static OrderFragment newInstance(Bundle bundle) {
        OrderFragment newFragment = new OrderFragment();
        newFragment.setArguments(bundle);
        return newFragment;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        status = getArguments().getString("status");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_base_subcribeorder;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        init();
    }

    @Override
    protected void updateViews() {

        onRefresh();
    }


    private void init() {
        session = UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapterWithProgress(adapter = new OrderMultiStyleAdapter2(getActivity()));
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_order_fragment_recyclerview_divider_decoration));
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.order_empty_view, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
        tv_content.setText("您还没有相关工单");
        recyclerView.setEmptyView(view);
        recyclerView.setErrorView(R.layout.view_error_refresh);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
//        adapter.setError(R.layout.view_error_click).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                adapter.resumeMore();
//            }
//        });

        recyclerView.setRefreshListener(this);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<WorkOrderModel>() {
            @Override
            public void onItemClick(View view, int position, WorkOrderModel model) {
                if (model.getOrderStatus().equals("waitPayDeposit") || model.getOrderStatus().equals("waitService") || (model.getOrderStatus().equals("cancelled") && model.getOpenTime() == 0)) {
                    startActivity(new Intent(getActivity(), BesPeakDetailsActivity.class).putExtra("storeId", model.getStoreId()).putExtra("orderNumber", model.getOrderNumber()).putExtra("userOrderId", model.getUserOrderId()));
                } else {
                    Intent ti = new Intent(getActivity(), OrderDetailsActivity3.class);
                    ti.putExtra("orderNumber", model.getOrderNumber());
                    ti.putExtra("userOrderId", model.getUserOrderId());
                    ti.putExtra("storeId", model.getStoreId());
                    startActivity(ti);
                }

            }
        });

    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(false);

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page = 1;
                getDataList(true);
            }
        }, 1000);
    }

    public void getDataList(final boolean isfirst) {

        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_MYORDERS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", session);
//        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("size", "10");
        params.addBodyParameter("status", status);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("hep", "所有订单==" + result);
                String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                String time = JsonUtil.getJsonValuesString(result, "serverTime");
                PhoneUtils.setTime(time);
                String list = JsonUtil.getJsonValuesString(data, "list");
                unPaidDepositTime = JsonUtil.getJsonValuesString(data, "unPaidDepositTime");
                try {
                    if (data != null) {
                        dataList.clear();
                        Gson gson = new GsonBuilder().create();
                        dataList = gson.fromJson(list, new TypeToken<List<WorkOrderModel>>() {
                        }.getType());

                        if (isfirst) {
                            adapter.clear();

                        }
                        if (dataList.size() < 9) {
                            adapter.stopMore();

                        }
                        adapter.addAll(dataList);
                    } else {
                        adapter.addAll(dataList);
                    }


                } catch (Exception e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    @Override
    public void reloadData() {
        //刷新
        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            if (adapter != null)
                adapter.pauseMore();
            return;
        }
        if (mIsMulti) {
            page = 1;
            getDataList(true);
        }
    }
}